package com.edward.volleydemo;

import android.util.Log;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;

/**
 * Created by Administrator on 2016/5/3.
 */
public class GsonRequest<T> extends Request<T> {
    private Response.Listener mListener;

    private Gson mGson;
    private Class<T> mClazz;

    public GsonRequest(int method, String url, Class<T> clazz, Response.Listener listener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        mListener = listener;

        mGson = new Gson();
        mClazz = clazz;
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse networkResponse) {
        try {
//            String jsonString = new String(networkResponse.data,
//                    HttpHeaderParser.parseCharset(networkResponse.headers));
            String jsonString = new String(networkResponse.data, "utf-8");
            Log.d("jsonString", jsonString);
            return Response.success(
                    mGson.fromJson(jsonString, mClazz),
                    HttpHeaderParser.parseCacheHeaders(networkResponse));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    protected void deliverResponse(T response) {
        mListener.onResponse(response);
    }
}
